package cn.heyige.backend.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.heyige.backend.dto.UserDTO;
import cn.heyige.backend.dto.UserDivinationSettingsDTO;
import cn.heyige.backend.dto.UserLoginDTO;
import cn.heyige.backend.dto.UserRegistrationDTO;
import cn.heyige.backend.entity.UserDO;
import cn.heyige.backend.mapper.FeedbackMapper;
import cn.heyige.backend.mapper.UserMapper;
import cn.heyige.backend.service.SimpleUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 简化版用户服务实现类
 * 
 * 专注于核心用户管理功能，提高系统性能和可维护性
 * 
 * @author CodeBuddy
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SimpleUserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements SimpleUserService {

    private final UserMapper userMapper;
    private final FeedbackMapper feedbackMapper;

    @Override
    public UserDTO register(UserRegistrationDTO registrationDTO) {
        // 参数校验
        if (registrationDTO == null || !StringUtils.hasText(registrationDTO.getUsername()) 
                || !StringUtils.hasText(registrationDTO.getPassword())) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }

        // 检查用户名是否已存在
        if (userMapper.existsByUsername(registrationDTO.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 创建新用户
        UserDO user = new UserDO();
        user.setUsername(registrationDTO.getUsername());
        user.setPassword(DigestUtil.bcrypt(registrationDTO.getPassword()));
        user.setBirthDate(registrationDTO.getBirthDate());
        user.setBirthLocation(registrationDTO.getBirthLocation());
        user.setCurrentCity(registrationDTO.getCurrentCity());
        user.setGender(registrationDTO.getGender());
        user.setMoodStatus(registrationDTO.getMoodStatus());
        
        // 保存用户
        userMapper.insert(user);
        log.info("用户注册成功: {}", user.getUsername());
        return convertToDTO(user);
    }

    @Override
    public UserDTO login(UserLoginDTO loginDTO) {
        // 参数校验
        if (loginDTO == null || !StringUtils.hasText(loginDTO.getUsername()) 
                || !StringUtils.hasText(loginDTO.getPassword())) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }

        // 根据用户名查找用户
        UserDO user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!DigestUtil.bcryptCheck(loginDTO.getPassword(), user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }

        log.info("用户登录成功: {}", user.getUsername());
        return convertToDTO(user);
    }

    @Override
    public UserDTO updateMoodStatus(Integer userId, String moodStatus) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        user.setMoodStatus(moodStatus);
        userMapper.updateById(user);
        log.info("用户心情状态更新成功: {}", user.getUsername());

        return convertToDTO(user);
    }

    @Override
    public UserDTO updateCurrentCity(Integer userId, String currentCity) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        user.setCurrentCity(currentCity);
        userMapper.updateById(user);
        log.info("用户当前城市更新成功: {}", user.getUsername());

        return convertToDTO(user);
    }

    @Override
    public UserDivinationSettingsDTO getUserDivinationSettings(Integer userId) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        UserDivinationSettingsDTO settings = new UserDivinationSettingsDTO();
        settings.setUserId(user.getId());
        settings.setUsername(user.getUsername());
        settings.setBirthLocation(user.getBirthLocation());
        settings.setCurrentCity(user.getCurrentCity());
        settings.setGender(user.getGender());
        settings.setMoodStatus(user.getMoodStatus());

        // 默认设置
        settings.setApplyFeedback(true);
        settings.setPreferredAiFactor(null);
        settings.setPreferredAiProvider(null);

        // 统计信息
        if (feedbackMapper != null) {
            try {
                // 获取用户的占卜总数
                long totalDivinations = feedbackMapper.countByUserId(userId);
                settings.setTotalDivinations((int) totalDivinations);

                // 获取用户的准确率
                Double accuracyRate = feedbackMapper.calculateUserAccuracyRate(userId);
                if (accuracyRate != null) {
                    settings.setAccuracyRate(accuracyRate);
                }
            } catch (Exception e) {
                log.warn("获取用户统计信息失败: {}", e.getMessage());
            }
        }

        return settings;
    }

    @Override
    public UserDivinationSettingsDTO updateUserDivinationSettings(Integer userId, UserDivinationSettingsDTO settings) {
        // 参数校验
        if (userId == null || settings == null) {
            throw new IllegalArgumentException("用户ID和占卜设置不能为空");
        }

        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 更新用户信息
        if (settings.getCurrentCity() != null) {
            user.setCurrentCity(settings.getCurrentCity());
        }

        if (settings.getMoodStatus() != null) {
            user.setMoodStatus(settings.getMoodStatus());
        }

        // 保存用户
        userMapper.updateById(user);

        // 返回更新后的设置
        return getUserDivinationSettings(userId);
    }

    /**
     * 将User实体转换为UserDTO
     * 
     * @param user 用户实体
     * @return 用户DTO
     */
    private UserDTO convertToDTO(UserDO user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setBirthDate(user.getBirthDate());
        dto.setBirthLocation(user.getBirthLocation());
        dto.setCurrentCity(user.getCurrentCity());
        dto.setGender(user.getGender());
        dto.setMoodStatus(user.getMoodStatus());
        return dto;
    }
}